/**

 * @author ChenJinZhu

 * @date 2023/3/26 14:36

 * @describe : 管线设备绘制功能

 */
let canvas = {}, ctx = {};
const image = new Image();

let offset = 0

// 定义管线宽度
const pipelineNumber = 15
// const PIPELINE_NUMBER = 15

// 定义管线绘制数组
let pipelinesDrawCollection = []

// 定义设备绘制数组
let equipmentsDrawCollection = []

// 定义当前选择绘制的类型 0为管线 1为设备，默认为管线
let selectDrawType = 0

// 定义设备图标清单
const equipmentsIcons = [
    {
        name: '管线',
        eId: 11,
        icon: 'line.png'
    },
    {
        name: '温度表',
        eId: 1,
        icon: 'thermometer.png'
    },
    {
        name: '压力表',
        eId: 2,
        icon: 'manometer.png'
    },
    {
        name: '接头',
        eId: 3,
        icon: 'joint.png'
    },
    {
        name: '直流阀',
        eId: 4,
        icon: 'direct_current_valve.png'
    },
    {
        name: '循环阀',
        eId: 5,
        icon: 'circulating_valve.png'
    },
    {
        name: '电动阀',
        eId: 6,
        icon: 'electric_valve.png'
    },
    {
        name: '开关阀',
        eId: 7,
        icon: 'on_off_valve.png'
    },
    {
        name: '热换机',
        eId: 8,
        icon: 'heat_exchanger.png'
    },
    {
        name: '热换机',
        eId: 9,
        icon: 'heat_exchanger1.png'
    },
    {
        name: '蓄水池',
        eId: 10,
        icon: 'reservoir.png'
    }
]

// 定义当前选择的设备图标
let currentSelectEquipment = {}

// 定义绘制管线类型：冷0 热1 水
let drawPipelineType = 0

// 当前选中管线ID
let currentSelectPipelineIndex = 0

// 定义管线函数工厂
class PipelineFactory {
    constructor(startX, startY, endX, endY, proportion, waterType) {
        this.startX = startX
        this.startY = startY
        this.endX = endX
        this.endY = endY
        // 管线绘制宽高比 true为横向管线  false为竖向管线
        this.proportion = proportion
        // 定义管线为热水还是冷水 0为冷水 1为热水
        this.waterType = waterType
    }
    get minX() {
        return Math.min(this.startX, this.endX);
    }
    get maxX() {
        return Math.max(this.startX, this.endX);
    }
    get minY() {
        return Math.min(this.startY, this.endY);
    }
    get maxY() {
        return Math.max(this.startY, this.endY);
    }
    get middleX() {
        return this.endX - (this.endX - this.startX) / 2
    }
    get middleY() {
        return this.endY - (this.endY - this.startY) / 2
    }

    // 绘制方法
    drawPipeline() {
        ctx.beginPath()
        ctx.moveTo(this.minX * devicePixelRatio, this.minY * devicePixelRatio)
        ctx.lineTo(this.maxX * devicePixelRatio, this.minY * devicePixelRatio)
        ctx.lineTo(this.maxX * devicePixelRatio, this.maxY * devicePixelRatio)
        ctx.lineTo(this.minX * devicePixelRatio, this.maxY * devicePixelRatio)
        ctx.lineTo(this.minX * devicePixelRatio, this.minY * devicePixelRatio)
        ctx.fillStyle = '#fff'
        ctx.fill()
        ctx.strokeStyle = '#fff'
        ctx.lineCap = 'square'
        ctx.lineWidth = 1 * devicePixelRatio
        ctx.stroke()

        ctx.beginPath()
        if (this.proportion) {
            ctx.moveTo(this.minX * devicePixelRatio, this.middleY * devicePixelRatio)
            ctx.lineTo(this.maxX * devicePixelRatio, this.middleY * devicePixelRatio)
            ctx.lineDashOffset = this.startX < this.endX ? -offset : offset;
        } else {
            ctx.moveTo(this.middleX * devicePixelRatio, this.minY * devicePixelRatio)
            ctx.lineTo(this.middleX * devicePixelRatio, this.maxY * devicePixelRatio)
            ctx.lineDashOffset = this.startY < this.endY ? -offset : offset;
        }

        ctx.strokeStyle = ['#0f42cc', '#ff4316'][this.waterType];
        ctx.lineWidth = 5;
        ctx.setLineDash([15, 15]);
        ctx.stroke()
    }

    // 判断当前点击位置是否在图形内部
    isInside(x, y) {
        return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY
    }
}




// 定义设备函数工厂
class EquipmentFactory {
    constructor(startX, startY, rotate, width, height) {
        this.startX = startX
        this.startY = startY
        // 旋转角度
        this.rotate = rotate
        // 图片宽高
        this.width = width
        this.height = height
    }

    drawEquipment() {
        image.src = require(`../assets/images/${currentSelectEquipment.icon}`)
        image.onload = () => {
            ctx.drawImage(image, this.startX, this.startY, image.width / 10, image.height / 10)
        }
    }
}


const drawPipelineEquipment = {
    init(element) {
        canvas = document.getElementById(element)
        ctx = canvas.getContext('2d')

        const w = 1200, h = 800;
        canvas.width = w * devicePixelRatio;
        canvas.height = h * devicePixelRatio;
        canvas.style.width = w + 'px';
        canvas.style.height = h + 'px';

        canvas.onmousedown = (e) => {
            mousedown(e);
        }
        draw()
        return canvas
    },

    // 修改管线类型（冷热水）
    changePipelineType: (type) => {
        drawPipelineType = type
    },

    // 更改绘制类型
    drawTypeChange(ele) {
        selectDrawType = ele.drawType
        if (selectDrawType) currentSelectEquipment = equipmentsIcons.find(item => item.eId === ele.eId)
    }
}

const mousedown = (e) => {
    const rect = canvas.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const clickY = e.clientY - rect.top;


    const shape = getPipeline(clickX, clickY)

    // if (selectDrawType) {
    //     const shapeEq = new EquipmentFactory(clickX, clickY)
    //     equipmentsDrawCollection.push(shapeEq)
    //     window.onmousemove = (evt) => {
    //         shapeEq.startX = evt.clientX - rect.left
    //         shapeEq.startY = evt.clientY - rect.top
    //     }
    // }


    if (shape) {
        // 拖动
        pipelineMove(e, clickX, clickY, rect, shape)

    } else {
        if (selectDrawType) {
            equipmentDraw(e, clickX, clickY, rect)

            // window.onmousemove = (evt) => {
            //     shapeEq.startX = evt.clientX - rect.left
            //     shapeEq.startY = evt.clientY - rect.top
            // }
        } else {
            pipelineDraw(e, clickX, clickY, rect)
        }

    }

    window.onmouseup = (e) => {
        // console.log(e)
        window.onmousemove = null
        window.onmouseup = null
    }
}

// 管线绘制
const pipelineDraw = (e, clickX, clickY, rect) => {
    const shape = new PipelineFactory(clickX, clickY)
    let shapeWidth = 0, shapeHeight = 0
    pipelinesDrawCollection.push(shape)

    window.onmousemove = (evt) => {
        shapeWidth = (evt.clientX - rect.left) - clickX
        shapeHeight = (evt.clientY - rect.top) - clickY
        let shapeDirection = Math.abs(shapeWidth) >= Math.abs(shapeHeight);
        if (shapeDirection) {
            shape.endX = evt.clientX - rect.left
            shape.endY = clickY + pipelineNumber
        } else {
            shape.endX = clickX + pipelineNumber
            shape.endY = evt.clientY - rect.top
        }
        shape.proportion = shapeDirection
        shape.waterType = drawPipelineType
    }
}

// 管线移动
const pipelineMove = (e, clickX, clickY, rect, shape) => {
    // const shape = getPipeline(clickX, clickY)
    // console.log('pipelineMove')
    createLineEdit(e.clientX, e.clientY)
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    const { startX, startY, endX, endY } = shape
    window.onmousemove = (evt) => {
        const distanceX = evt.clientX - rect.left - clickX
        const distanceY = evt.clientY - rect.top - clickY
        shape.startX = startX + distanceX
        shape.startY = startY + distanceY
        shape.endX = endX + distanceX
        shape.endY = endY + distanceY

        const tipText = document.getElementById('tipText')
        if (tipText) {
            tipText.style.left = evt.clientX + 'px'
            tipText.style.top = evt.clientY + 10 + 'px'
        }
    }
}

// 设备绘制
const equipmentDraw = (e, clickX, clickY, rect) => {
    const shapeEq = new EquipmentFactory(clickX, clickY)
    equipmentsDrawCollection.push(shapeEq)

    console.log(equipmentsDrawCollection)
}


// 鼠标点击canvas查看是否点击到了已经绘制的路线，若是，则返回相关线的对象，若否，返回null
const getPipeline = (x, y) => {
    for (let i = pipelinesDrawCollection.length - 1; i >= 0; i--) {
        const ppl = pipelinesDrawCollection[i]
        if (ppl.isInside(x, y)) {
            currentSelectPipelineIndex = i
            return ppl
        }
    }
    return null
}

// 一直开启画布绘制功能
const draw = () => {
    requestAnimationFrame(draw)
    // ctx.clearRect(0, 0, canvas.width, canvas.height)
    for (const pp of pipelinesDrawCollection) {
        pp.drawPipeline()
    }
    for (const eq of equipmentsDrawCollection) {
        eq.drawEquipment()
    }
    offset++;
    if (offset > 300) {
        offset = 0;
    }
}

// 创建管线点击事件弹窗
const createLineEdit = (x, y) => {
    removeLineEdit()
    let tipText = document.createElement('div')
    tipText.classList.add('tip-text-content')
    tipText.innerHTML = `<div class="tip-text" id="tipText" style="top: ${y + 10}px;left: ${x}px;">
                            <p>
                                <span id="pipelineDelete">删除</span>
                                <span id="buttonCancel">取消</span>
                            </p>
                         </div>`
    document.body.appendChild(tipText)

    document.getElementById('pipelineDelete').onclick = (e) => {
        pipelinesDrawCollection.splice(currentSelectPipelineIndex, 1)
        removeLineEdit()
    }
    document.getElementById('buttonCancel').onclick = (e) => {
        removeLineEdit()
    }
}

// 移除管线事件弹窗
const removeLineEdit = () => {
    const popup = document.querySelector('.tip-text-content')
    if (popup) document.body.removeChild(popup)
}

export default drawPipelineEquipment
